package tools;

import java.io.Serializable;
import java.util.Set;
import java.util.TreeMap;

import adaptors.TabReference;



public class TabLibrary implements Serializable	{

	private static final long serialVersionUID = 1L;
	private TreeMap<String, TreeMap<String, TabReference>> bandMap;
	
	public TabLibrary()	{
		bandMap = new TreeMap<String, TreeMap<String, TabReference>>();
	}
	
	public boolean addTab(Tab t)	{
		String bandName = t.getBandName();
		bandName = bandName.toLowerCase();

		if( bandMap.containsKey(bandName) )	{
			TreeMap<String,TabReference> bandTabSet = bandMap.get(bandName);
			System.out.println("+ Adding song to existing band");
			bandTabSet.put(t.getSongName(), t.getReference());
			return true;
		}
		else	{
			TreeMap<String,TabReference> bandTabSet = new TreeMap<String,TabReference>();
			bandTabSet.put(t.getSongName(), t.getReference());
			bandMap.put(bandName, bandTabSet);
			System.out.println("+ Added song to *NEW* band");
			return true;
		}
	}

	public Set<String> getAllBandEntries()	{
		return bandMap.keySet();
	}
	
	public TreeMap<String, TabReference> findBand(String bandName)	{
		return bandMap.get(bandName);
	}

	public boolean removeTab(TabReference tabReference) {		
		TreeMap<String, TabReference> tabMap = null;
		
		if( bandMap.containsKey(tabReference.getBandName().toLowerCase()) )
			tabMap = bandMap.get(tabReference.getBandName().toLowerCase());
		else	{
			System.out.println("TAB MAP IS NULL!");
			return false;
		}
			
		if( tabMap.containsKey(tabReference.getSongName()) )	{
			return removeAllOccurrancesOfTab(tabReference);
		}
		
		return false;
	}
	
	public boolean removeAllOccurrancesOfTab(TabReference tr)	{
		TreeMap<String, TabReference> tabMap = bandMap.get(tr.getBandName().toLowerCase());
		
		// Remote primary entry of tab
		if( tabMap.remove(tr.getSongName()) == null )
			return false;
		

		// TODO Add routines to delete other occurrences of tabs from data structures
		
		return true;
		
	}
	
	public TreeMap<String, TabReference> removeBand(String bandName)	{
		return bandMap.remove(bandName);
	}
}
